package com.happyghost.juc.synchronizeddemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SynchroniedDemo2 {

    public void method1() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                System.out.print(" " + i);
            }
        }
    }

    /**
     * 对于以下代码，两个线程调用了不同对象的同步代码块，因此这两个线程就不需要同步。从输出结果可以看出，两个线程交叉执行。
     * @param args
     */
    public static void main(String[] args) {
        SynchroniedDemo2 demo1 = new SynchroniedDemo2();
        SynchroniedDemo2 demo2 = new SynchroniedDemo2();
        SynchroniedDemo2 demo3 = new SynchroniedDemo2();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> demo1.method1());
        executorService.execute(() -> demo2.method1());
        executorService.execute(() -> demo3.method1());

        //result
        //0 1 2 3 4 5 6 0 1 0 1 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9 7 8 9
    }
}
